﻿using ClassMySQL.Classes;
using Library.Classes;
using System.ComponentModel;
using System.Data;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;

namespace Library.Windows
{
    /// <summary>
    /// Логика взаимодействия для Authors.xaml
    /// </summary>
    public partial class Authors : Window, INotifyPropertyChanged
    {
        private bool _editMode = false;
        private static int _id = 0;
        public Authors()
        {
            InitializeComponent();
            listAuthors.ItemsSource = LoadAuthor();
            listAuthors.Items.SortDescriptions.Add(new SortDescription("LastName", ListSortDirection.Ascending));
            lastName.Focus();
        }

        public event PropertyChangedEventHandler? PropertyChanged;

        public void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        private static List<Author>? LoadAuthor()
        {
            DataTable dt = ServerMySQL.GetDataTable("authors");
            List<Author> authors = new List<Author>();
            if (dt.Rows.Count != 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    Author author = new Author(
                        id: Convert.ToInt32(row[0]),
                        lastName: row[1].ToString(),
                        firstName: row[2].ToString(),
                        patronymic: row[3].ToString(),
                        decsription: row[4].ToString()
                        );
                    authors.Add(author);
                }
            }
            return authors;
        }

        private void addAuthor_Click(object sender, RoutedEventArgs e)
        {
            if (lastName.Text == string.Empty)
            {
                MessageBox.Show("Укажите фамилию", "Заполните обязательные поля",
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            Author author = new Author(
                id: _id,
                lastName: lastName.Text,
                firstName: firstName.Text,
                patronymic: patronymicName.Text,
                decsription: descriptionAuthor.Text
                );
            if (_editMode)
            {
                if (SendToServer.EditAuthor(author))
                {
                    ClearText();
                    UpdateUi();
                    _editMode = false;
                }
                else
                {
                    MessageBox.Show("Ошибка записи", "Неудача",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            else
            {
                if (SendToServer.AddAuthor(author))
                {
                    ClearText();
                }
                else
                {
                    MessageBox.Show("Ошибка записи", "Неудача",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            
            listAuthors.ItemsSource = LoadAuthor();
        }
        private void ClearText()
        {
            // Очистка полей ввода (если запись была успешной)
            lastName.Clear();
            firstName.Clear();
            patronymicName.Clear();
            descriptionAuthor.Clear();
        }

        private void UpdateUi()
        {
            GroupHeader.Header = "Добавление нового автора";
            addAuthor.Content = "Добавить автора";
        }

        private void listAuthors_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (listAuthors.SelectedItems.Count > 0)
            {
                Author? author = listAuthors.SelectedItem as Author;
                infoLastName.Text = author.LastName;
                infoFirstName.Text = author.FirstName;
                infoPatronymic.Text = author.Patronymic;
                infoDescription.Text = author.Description;
            }
        }

        private void ChangeRow_Click(object sender, RoutedEventArgs e)
        {
            if (listAuthors.SelectedItems.Count > 0)
            {
                _editMode = true;   // Установка режима редактирования

                GroupHeader.Header = "Обновить данные автора";
                addAuthor.Content = "Обновить данные";
                Author? author = listAuthors.SelectedItem as Author;
                lastName.Text = author.LastName;
                firstName.Text = author.FirstName;
                patronymicName.Text = author.Patronymic;
                descriptionAuthor.Text = author.Description;

                // Получаем идентификатор (id) выделенного автора
                _id = author.Id;
            }
        }
    }
}
